package controller.servlet.member;

import java.io.IOException;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.RoleDAO;
import model.dao.UserDAO;
import model.dao.service.RoleDAOService;
import model.dao.service.UserDAOService;
import model.entities.Role;
import model.entities.User;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.FileUpload;

/**
 *
 * @author Admin
 */
public class UpdateProfile extends HttpServlet {

    private final UserDAOService USER_SERVICE = UserDAO.getInstance();
    private final RoleDAOService ROLE_SERVICE = RoleDAO.getInstance();

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String action = request.getParameter("action");
        if (action == null) {
            updateAvatar(request, response);
        } else {
            switch (action) {
                case "Update Info":
                    updateProfile(request, response);
                    break;
                case "Change Password":
                    updatePassword(request, response);
                    break;
            }
        }
    }

    private void updateProfile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User currentUser = (User) request.getSession().getAttribute(util.Constants.CURRENT_USER);
        int userID = currentUser.getUserID();
        String userName = currentUser.getUserName();
        String fullName = request.getParameter("fullName");
        String day = request.getParameter("birthday_day");
        String month = request.getParameter("birthday_month");
        String year = request.getParameter("birthday_year");
        java.sql.Date birthday = util.Support.convertToDate(day, month, year);
        boolean gender = request.getParameter("gender").equals("male");
        String idCard = request.getParameter("idCard");
        String address = request.getParameter("address");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        Role role = ROLE_SERVICE.getRoleByID(4);
        User user = new User(userID, userName, currentUser.getPwd(), fullName, birthday, gender, idCard, address, email, phone, currentUser.getPathImage(), role, null, true);
        if (USER_SERVICE.updateProfile(user)) {
            request.setAttribute(util.Constants.PAGE, "result");
            request.setAttribute(util.Constants.PAGE_RESULT, "profile");
            request.removeAttribute(util.Constants.MSG_RESULT);
            request.setAttribute(util.Constants.MSG_RESULT, "You have successfully updated !!!");
            request.getSession().setAttribute(util.Constants.CURRENT_USER, user);
            request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
        } else {
            request.setAttribute(util.Constants.PAGE, "result");
            request.setAttribute(util.Constants.PAGE_RESULT, "profile");
            request.removeAttribute(util.Constants.MSG_RESULT);
            request.setAttribute(util.Constants.MSG_RESULT, "You have update profile failed !!!");
            request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
        }
    }

    private void updateAvatar(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute(util.Constants.CURRENT_USER);
        if (currentUser != null) {
            int userID = currentUser.getUserID();
            String userName = currentUser.getUserName();
            String pathImage;
            ServletFileUpload fileUpload = new ServletFileUpload();
            try {
                FileItemIterator itr = fileUpload.getItemIterator(request);
                while (itr.hasNext()) {
                    FileItemStream itemStream = itr.next();
                    if (!itemStream.isFormField()) {
                        //do file upload specific process
                        String realPath = getServletContext().getRealPath("/");
                        String filePath = realPath.replace("\\build\\web", "\\web\\img\\avatar");//Duong dan luu file anh
                        String imageName = itemStream.getName();
                        StringTokenizer token = new StringTokenizer(imageName, ".");
                        String fileNameExtension = "";
                        while (token.hasMoreElements()) {
                            fileNameExtension = token.nextElement().toString();
                        }
                        pathImage = "img/avatar/" + userName + "." + fileNameExtension;
                        User user = new User(userID, userName, null, null, null, true, null, null, null, null, pathImage, null, null, true);
                        if (!FileUpload.processFile(filePath, itemStream, userName, fileNameExtension) || !USER_SERVICE.updateAvatar(user)) {
                            request.setAttribute(util.Constants.PAGE, "result");
                            request.setAttribute(util.Constants.PAGE_RESULT, "profile");
                            request.removeAttribute(util.Constants.MSG_RESULT);
                            request.setAttribute(util.Constants.MSG_RESULT, "Update avatar failed !!!");
                            request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
                        } else {
                            request.setAttribute(util.Constants.PAGE, "result");
                            request.setAttribute(util.Constants.PAGE_RESULT, "profile");
                            request.removeAttribute(util.Constants.MSG_RESULT);
                            request.setAttribute(util.Constants.MSG_RESULT, "Changes avatar successfully !!!");
                            request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
                        }
                    }
                }
            } catch (FileUploadException | IOException | ServletException e) {
                e.printStackTrace();
            }
        } else {
            response.getWriter().print("The deo nao ko co session");
        }
    }

    private void updatePassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User currentUser = (User) request.getSession().getAttribute(util.Constants.CURRENT_USER);
        int userID = currentUser.getUserID();
        String userName = currentUser.getUserName();
        String currentPwd = request.getParameter("currentPwd");
        String currentPwdEncrypt = util.MD5.encryptMD5(currentPwd);
        if (currentUser.getPwd().equals(currentPwdEncrypt)) {
            String pwd = request.getParameter("newPwd");
            String password = util.MD5.encryptMD5(pwd);
            User user = new User(userID, userName, password, null, null, true, null, null, null, null, null, null, null, true);
            if (USER_SERVICE.updatePassword(user)) {
                request.setAttribute(util.Constants.PAGE, "result");
                request.setAttribute(util.Constants.PAGE_RESULT, "profile");
                request.removeAttribute(util.Constants.MSG_RESULT);
                request.setAttribute(util.Constants.MSG_RESULT, "You have successfully updated Password !!!");
                request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
            } else {
                request.setAttribute(util.Constants.PAGE, "result");
                request.setAttribute(util.Constants.PAGE_RESULT, "profile");
                request.removeAttribute(util.Constants.MSG_RESULT);
                request.setAttribute(util.Constants.MSG_RESULT, "You have update password failed !!!");
                request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
            }
        } else {
            request.setAttribute(util.Constants.PAGE, "result");
            request.setAttribute(util.Constants.PAGE_RESULT, "changepass");
            request.removeAttribute(util.Constants.MSG_RESULT);
            request.setAttribute(util.Constants.MSG_RESULT, "Current password is wrong !!!");
            request.getRequestDispatcher(util.Constants.URL_INDEX).forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
